<template>
    <preDefLineGradientDlg ref="refpreDefLineGradientDlg" />
    <div class='FillStyleContainer'>
        <el-radio-group v-model="fillMode" @change="OnSelFillMode($event)">
            <el-radio label="none" size="large" border style="width:100%;">none</el-radio>
            <el-radio label="solid" size="large" border style="width:100%;">solid</el-radio>
            <el-radio label="Gradient" size="large" border style="width:100%;">Gradient</el-radio>
        </el-radio-group>
        <div style="margin:0;padding:0; width:100%;height:2px;background-color:#8aabe5;overflow:hidden;"></div>
        <div v-if="fillMode == 'solid'" style="width:100%">
            <el-row type="flex" justify="space-between" style="font-size:12px;">
                <el-col :span="4">
                    <label for="fillcolor_id" >填充色</label>
                </el-col>
                <el-col :span="20">
                    <el-color-picker v-model="solidFillColor" show-alpha :predefine="predefineColors"
                        @change="onSelFillColor($event)"  id="fillcolor_id">
                    </el-color-picker>
                </el-col>
            </el-row>
        </div>

        <div v-if="fillMode == 'Gradient'" style="width:100%;padding: 0px;">
            <el-row style="font-size:12px;">
                <el-radio-group v-model="gradientType" @change="OnGradientMode($event)">
                    <el-radio label="lineGradient" size="large" border style="width:30%;">线性</el-radio>
                    <el-radio label="radialGradient" size="large" border style="width:30%;">辐射</el-radio>
                </el-radio-group>
            </el-row>

            <el-row type="flex" justify="space-between" style="font-size:12px;">
                <el-col :span="5">
                    <label for="preDefMode_id">预设样式</label>
                </el-col>
                <el-col :span="19">
                    <el-select id="preDefMode_id" @focus="onFocus($event)" style="width:90%;">
                        <!-- <el-option v-for="item in preDefGradientItemArr" :key="item.id" :label="item.propValue" :value="item.id"
                        style="width:80%;">
                    </el-option> -->
                    </el-select>
                </el-col>
            </el-row>

            <el-row type="flex" justify="space-between" style="font-size:12px;">
                <el-col :span="5">
                    <label for="gradientStPoint">起点</label>
                </el-col>
                <el-col :span="19">
                    <el-input id="gradientStPoint" v-model="stPoint" :ref="stPointInput" style="width:67%;"></el-input>
                    <el-tooltip class="item" effect="light" content="图中取点" placement="top" :show-after=1000>
                        <el-button @click="onSelPointOnMap('st')">...</el-button>
                    </el-tooltip>
                </el-col>
            </el-row>
            <el-row type="flex" justify="space-between" style="font-size:12px;">
                <el-col :span="5">
                    <label for="gradientEndPoint">终点</label>
                </el-col>
                <el-col :span="19">
                    <el-input id="gradientEndPoint" v-model="endPoint" :ref="endPointInput" style="width:67%;"></el-input>
                    <el-tooltip class="item" effect="light" content="图中取点" placement="top" :show-after=1000>
                        <el-button @click="onSelPointOnMap('end')">...</el-button>
                    </el-tooltip>
                </el-col>
            </el-row>
            <el-row type="flex" justify="space-between" style="font-size:12px;">
                <el-col :span="5">
                    <label for="angleinput">角度</label>
                </el-col>
                <el-col :span="19">
                    <el-input-number id="angleinput" :min="0" :max="360" :step=10 v-model="rotAngle"
                        controls-position="right" @change="onSelChgAngle($event)" style="width:90%;">
                    </el-input-number>
                </el-col>
            </el-row>

            <el-row type="flex" justify="space-between" style="font-size:12px;">
                <el-col :span="5">
                    <label for="gradientStopIndx_sel">光圈</label>
                </el-col>
                <el-col :span="19">
                    <el-select id="gradientStopIndx_sel" v-model="selGradientStopIndx"
                        @change="onSelChgGradientIndx($event)" style="width:28%;">
                        <el-option v-for="item in GradientStopItemArr" :key="item.idx" :label="item.stop"
                            :value="item.idx" style="width:100%;">
                        </el-option>
                    </el-select>

                    <el-color-picker v-model="gradientColor" show-alpha :predefine="predefineColors"
                        @change="onSelGradientColor($event)">
                    </el-color-picker>
                    <el-tooltip class="item" effect="light" content="增加渐变光圈" placement="top-start">
                        <el-button icon="Plus" style="position: relative; left:5px;padding-right:5px;"
                            @click="addGradient()">
                        </el-button>
                    </el-tooltip>

                    <el-tooltip class="item" effect="light" content="删除渐变光圈" placement="top-start">
                        <el-button icon="Minus" @click="delGradient()"
                            style="position: relative; left:5px;padding-right:5px;">
                        </el-button>
                    </el-tooltip>
                </el-col>
            </el-row>
            <canvas id="GradientCanvas" width="300" height="30" z-index="3"></canvas>

        </div>
    </div>
</template>
<script setup>
import { useRouter } from 'vue-router';
const router = useRouter();

import { ref, onMounted } from 'vue'
import preDefLineGradientDlg from './preDefLineGradientDlg.vue';

import lgxcom from '../../script/canvas/common/common.js'
import  {LGXEnums}  from '../../script/canvas/common/sysenum.js'

import globalConst from '../../script/canvas/common/globalConst'
var global = globalConst.GlobalConst;

import { ElRadio, ElRadioGroup } from 'element-plus'

const defaultStopArr = [
    { idx: 0, stop: '0', color: 255255 },
    { idx: 1, stop: '1', color: 16777215 }];

const selPointMode = ref("none");
const stPoint = ref("(0,0)");
const endPoint = ref("(0,0)")
const refpreDefLineGradientDlg = ref(null);
const refPatternSettingDlg = ref(null);
const isPatterSettingDlgOpen = ref(true)

onMounted(() => {
    console.log("fill onMounted");
    refpreDefLineGradientDlg.value.notifyFunc = initDatas;
})


var initDatas = function () {
    console.log("fillstyle init **************");
    let sysPatterArr = [];
    let idx = 0;
    PatternFillModeItemArr.value = [];
    sysPatterArr.forEach(pat => {
        PatternFillModeItemArr.value.push({ id: ++idx, propValue: pat });
    });

    let rst = window.mainctl.m_pGetDataINTF.getFillDefDatas(0);
    if (!rst) {
        return;
    }
    fillMode.value = rst.fillStyle;
    selGradientStopIndx.value = 0;
    if (fillMode.value == 'Gradient' && rst.gradientInfo) {
        gradientType.value = rst.childmode;
        rotAngle.value = rst.gradientInfo.degree;
        GradientStopItemArr.value = rst.gradientInfo.stopColorArr;
        GradientStopItemArr.value = [];
        let idx = 0;
        rst.gradientInfo.stopColorArr.forEach(ele => {
            let stop = ele.stop;
            let color = ele.color.toValue();
            let item = {idx,stop,color};
            GradientStopItemArr.value.push(item);
            idx++;
        });
    }
    else {
        GradientStopItemArr.value = [
            { idx: 0, stop: '0', color: 255255 },
            { idx: 1, stop: '1', color: 16777215 }];
    }

    let fillCV = parseInt(rst.fillColor);
    let fillCOBJ = new lgxcom.LGXColor();
    fillCOBJ.setColorByValue(fillCV);
    solidFillColor.value = fillCOBJ.toHexString();

    let stopCount = GradientStopItemArr.value.length;
    if (stopCount > 1) {
        let t = GradientStopItemArr.value[0];
        fillCV = parseInt(t.color);
        fillCOBJ = new lgxcom.LGXColor();
        fillCOBJ.setColorByValue(fillCV);
        gradientColor.value = fillCOBJ.toHexString();
    }

    if (rst.gradientInfo) {
        let sx = rst.gradientInfo.stPt.x.toFixed(2);
        let sy = rst.gradientInfo.stPt.y.toFixed(2);
        stPoint.value = sx + "," + sy;

        sx = rst.gradientInfo.endPt.x.toFixed(2);
        sy = rst.gradientInfo.endPt.y.toFixed(2);
        endPoint.value = sx + "," + sy;
    }
    else {
        stPoint.value = "";
        endPoint.value = "";
    }

    paintGradient();
}

const onFocus = (item) => {
    console.log("select pre def gradient ");
    refpreDefLineGradientDlg.value.visible = true;
    refpreDefLineGradientDlg.value.paintGradient();
}

const onSelPointOnMap = (mode) => {
    selPointMode.value = mode;
    window.mainctl.setMapWorkMode(LGXEnums.LGXWorkMode.PickPointMode);
}

const onSetPatterDetail = () => {
    refPatternSettingDlg.value.mapctrl = window.mainctl;
    refPatternSettingDlg.value.initDatas();
    refPatternSettingDlg.value.visible = true;
    isPatterSettingDlgOpen.value = true;
}

var notifySelGraph = function (mousePoint, list) {
    console.log("fillStyle act2PickGraphs --------------");
    console.log(selPointMode.value);
    if (selPointMode.value == "none") {
        this.initDatas();
    }
    else {

        let subPropname = "";
        let sx = mousePoint.x.toFixed(2);
        let sy = mousePoint.y.toFixed(2);
        let coordDesc = sx + "," + sy;
        if (selPointMode.value == 'st') {
            stPoint.value = coordDesc;
            subPropname = "st";
        }
        else if (selPointMode.value == 'end') {
            endPoint.value = coordDesc;
            subPropname = "end";
        }

        if (subPropname && subPropname.length > 0) {
            let propval = { subProp: subPropname, val: mousePoint };
            let cmd = { propname: 'gradient_stopPos', propval };
            window.mainctl.m_pEditINTF.modifyGraphStyle(cmd);
            if (fillMode.value == "Gradient") {
                paintGradient();
            }
        }
        selPointMode.value = "none";
    }
}


var modifyFillMode = function () {
    console.log("modifyFillMode*****");
    var propname = "fill";
    var propval = 0;
    if (fillMode.value == "none")
        propval = { 'fillMode': 'none' };
    else if (fillMode.value == "solid") {
        let colorval = parseColorStr(solidFillColor.value);
        propval = { 'fillMode': 'solid', color: colorval };
    }
    else if (fillMode.value == "pattern") {
        propval = { 'fillMode': 'pattern', name: PatternFillMode.value };
    }
    else if (fillMode.value == "Gradient") {
        // let stopArr = [];
        // .forEach(ele => {
        //     let stop = ele.stop;
        //     let color = ele.color.toValue();
        //     let item = {idx,stop,color};
        // });
        propval = { 'fillMode': gradientType.value, stopArr:GradientStopItemArr.value};
    }
    var cmd = { propname, propval };
    window.mainctl.m_pEditINTF.modifyGraphStyle(cmd);
    if (fillMode.value == "Gradient") {
        paintGradient();
    }
}

var onSelPatternFillMode = function (item) {
    console.log("onSelPatternFillMode*********************");
    modifyFillMode();
}

var OnGradientMode = function (item) {
    selGradientStopIndx.value = 1;
    modifyFillMode();
}
var OnSelFillMode = function (item) {
    if (fillMode.value == "Gradient" && GradientStopItemArr.value.length < 2) {
        GradientStopItemArr.value = defaultStopArr;
    }
    modifyFillMode();
}

var onSelFillColor = function (item) {
    var propname = 'fillColor';
    modifyFillColor(propname, item);
}


var onSelChgAngle = function (item) {
    console.log("change gradient color angle:" + item);
    let propname = "GradientAngle";
    let propval = item;
    var cmd = { propname, propval };
    window.mainctl.m_pEditINTF.modifyGraphStyle(cmd);
}

var onSelChgGradientIndx = function (item) {
    var propname = 'gradient_end_color';
    console.log("selGradientStopIndx:" + selGradientStopIndx.value);
}

var onSelGradientColor = function (item) {
    let idx = selGradientStopIndx.value;
    let stopArr = GradientStopItemArr.value;
    let stop = stopArr[idx];
    if (stop) {
        stop.color = parseColorStr(item);
        modifyFillMode();
    }
}



var modifyFillColor = function (propname, item) {
    console.log(item);

    let pos1 = item.indexOf('(');
    let pos2 = item.indexOf(')');
    var rgbaStr = item.substr(pos1 + 1, pos2 - pos1 - 1);
    var rgbStrLst = rgbaStr.split(',');
    var lgxColor = new lgxcom.LGXColor();
    lgxColor.red = parseInt(rgbStrLst[0]);
    lgxColor.green = parseInt(rgbStrLst[1]);
    lgxColor.blue = parseInt(rgbStrLst[2]);
    lgxColor.alpha = 255;
    var propval = lgxColor.toValue();
    var cmd = { propname, propval };
    window.mainctl.m_pEditINTF.modifyGraphStyle(cmd);
}

var parseColorStr = function (item) {
    let pos1 = item.indexOf('(');
    let pos2 = item.indexOf(')');
    var rgbaStr = item.substr(pos1 + 1, pos2 - pos1 - 1);
    var rgbStrLst = rgbaStr.split(',');
    var lgxColor = new lgxcom.LGXColor();
    lgxColor.red = parseInt(rgbStrLst[0]);
    lgxColor.green = parseInt(rgbStrLst[1]);
    lgxColor.blue = parseInt(rgbStrLst[2]);
    lgxColor.alpha = 255;
    var colorval = lgxColor.toValue();
    return colorval;
}



var addGradient = function () {
    let nxtIdx = -1;
    let stopCount = GradientStopItemArr.value.length;
    if (selGradientStopIndx.value == 0) {
        nxtIdx = 1;
    }
    else if (selGradientStopIndx.value == stopCount - 1) {
        nxtIdx = stopCount - 2;
    }
    else {
        nxtIdx = selGradientStopIndx.value + 1;
    }
    if (nxtIdx < 0) {
        return 1;
    }

    let stop1 = GradientStopItemArr.value[selGradientStopIndx.value];
    let stop2 = GradientStopItemArr.value[nxtIdx];
    let nxtStopProportion = (parseFloat(stop1.stop) + parseFloat(stop2.stop)) / 2.0;
    let tmpColor = new lgxcom.LGXColor();
    let stopItem = { idx: -1, stop: nxtStopProportion, color:tmpColor.toValue() };
    GradientStopItemArr.value.push(stopItem);

    let sortList = GradientStopItemArr.value.sort(function (p1, p2) {
        let inlayIdx1 = p1.stop;
        let inlayIdx2 = p2.stop;
        if ((inlayIdx1 - inlayIdx2) > 0) {
            return 1;
        }
        else {
            return -1;
        }
    }
    );
    for (let i = 0; i < sortList.length; i++) {
        let t = sortList[i];
        t.idx = i;
        if (t.stop == nxtStopProportion) {
            selGradientStopIndx.value = i;
        }
    }
    GradientStopItemArr.value = sortList;
    modifyFillMode();
}

var delGradient = function () {
    if (selGradientStopIndx.value == 0
        || selGradientStopIndx.value == GradientStopItemArr.value.length - 1) {
        return;
    }

    GradientStopItemArr.value.splice(selGradientStopIndx.value, 1);
    if (selGradientStopIndx.value > 0) {
        selGradientStopIndx.value -= 1;
    }
    modifyFillMode();
    console.log(GradientStopItemArr.value);
}

var paintGradient = function () {
    var map = document.getElementById("GradientCanvas");
    if (!map) {
        return;
    }
    var ctx = map.getContext("2d");
    let w = 250;
    let h = 30;

    let color = new lgxcom.LGXColor();
    let grd = ctx.createLinearGradient(0, 0, w, 0);
    let stopArr = GradientStopItemArr.value;
    for (let i = 0; i < stopArr.length; i++) {
        let stop = stopArr[i];
        let partion = parseFloat(stop.stop);
        color.setColorByValue(parseInt(stop.color));
        grd.addColorStop(partion, color.toHexString());
    }

    ctx.fillStyle = grd;
    ctx.fillRect(0, 0, w, h);
}


const fillMode = ref("none")
const selGradientStopIndx = ref(0)
const gradientType = ref('lineGradient')
const PatternFillMode = ref('')
const rotAngle = ref(0)
const GradientStopItemArr = ref([
    { idx: 0, stop: '0', color: 255255 },
    { idx: 1, stop: '1', color: 16777215 }
])

const solidFillColor = ref('rgba(255, 69, 0, 0.68)')
const gradientColor = ref('rgba(255, 69, 255, 1)')

const PatternFillModeItemArr = ref([
    { id: '0', propValue: 'l-r-slope' },
    { id: '1', propValue: 'r-l-slope' },
    { id: '2', propValue: 'l-r-line' },
    { id: '3', propValue: 'b-t-line' }
])

const predefineColors = ref(global.sysPreDefColors)


defineExpose({
    initDatas,
    notifySelGraph
});
</script>